package org.tools.common;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 
 * 线程工具
 *
 * <pre> 
 * 构建组：e-tools
 * 作者：eddy
 * 邮箱：1546077710@qq.com
 * 日期：2017年4月23日-下午6:06:53
 * 版权：E源时代
 * </pre>
 */
public class ThreadUtil {
	
	public static final int  DEFAULT_THREAD_COUNT = 5;
	public static final int  THREAD_TYPE_SINGLE = 1;
	public static final int  THREAD_TYPE_FIXED = 2;
	public static final int  THREAD_TYPE_CACHED = 3;
	private static ExecutorService singleThreadExecutor = null;
	private static ExecutorService fixedThreadPool = null;
	private static ExecutorService cachedThreadPool = null;
	
	static{
		initFixedThreadPool(DEFAULT_THREAD_COUNT);
		initSingleThreadExecutor();
		initCachedThreadPool();
	}
	
	public static void initSingleThreadExecutor(){
		singleThreadExecutor = Executors.newSingleThreadExecutor();
	}
	
	public static void initFixedThreadPool(int nThreads){
		fixedThreadPool = Executors.newFixedThreadPool(nThreads);
	}
	
	public static void initCachedThreadPool(){
		cachedThreadPool = Executors.newCachedThreadPool();
	}
	
	public static void execute(int type, Runnable runnable){
		switch (type) {
		case THREAD_TYPE_SINGLE:
			if(null == singleThreadExecutor){
				initSingleThreadExecutor();
			}
			singleThreadExecutor.execute(runnable);
			break;
		case THREAD_TYPE_FIXED:
			if(null == fixedThreadPool){
				initFixedThreadPool(DEFAULT_THREAD_COUNT);
			}
			fixedThreadPool.execute(runnable);
			break;
		case THREAD_TYPE_CACHED:
			if(null == cachedThreadPool){
				initCachedThreadPool();
			}
			cachedThreadPool.execute(runnable);
			break;
			
		default:
			if(null == singleThreadExecutor){
				initSingleThreadExecutor();
			}
			singleThreadExecutor.execute(runnable);
			break;
		}
	}
}
